#!/usr/bin/python
#-----------------------------------------------------------------------------|
"""
Expenses main module.

License GPL.
"""
__author__ = "ralfoide@gmail.com"

import os
import sys
import getopt

from exp.log import Log
from exp.parser import Parser
from exp.analyze import Analyze
from exp.settings import ExpenseSettings

#------------------------
class Expenses(object):
    _USAGE = """
Expenses [-h] 

Options:
    -h, --help:    This help
    -v, --verbose: Verbose logging
    -d, --dir:     Process all files in given directory
    -c, --config:  Configuration file (default: %(_configPaths)s) 
"""
    
    def __init__(self):
        self._log = None
        self._verbose = Log.LEVEL_NORMAL
        self._dir = None
        self._configPaths = [ "/etc/expenses.rc",
                              os.path.expanduser(os.path.join("~", ".expensesrc")) ]

    def _UsageAndExit(self, msg=None):
        """
        Prints usage string and exit program.
        """
        if msg:
            print msg
        print self._USAGE % self.__dict__
        sys.exit(2)

    def ParseArgs(self, argv):
        """
        Parses command line arguments.
        """
        try:
            options, args = getopt.getopt(argv[1:],
                                          "hHvd:c:",
                                          ["help", "verbose", "dir=", "config="])
            for opt, value in options:
                if opt in ["-h",  "-H", "--help"]:
                    self._UsageAndExit()
                elif opt in ["-v", "--verbose"]:
                    self._verbose = Log.LEVEL_VERY_VERBOSE
                elif opt in ["-d", "--dir"]:
                    if not self._dir: self._dir = []
                    self._dir.append(value)
                elif opt in ["-c", "--config"]:
                    self._configPaths = [ value ]
        except getopt.error, msg:
            self._UsageAndExit(msg)

    def Run(self):
        """
        Do stuff.
        """
        self._log = Log(verbose_level=self._verbose, use_stderr=self._verbose)
        self._log.Debug("Started")
        self._settings = ExpenseSettings(self._log).Load(self._configPaths)
        self._settings.GetVariables()
        
        p = Parser(self._log)
        for dir in self._dir:
            p.ParseDir(dir)
        a = Analyze(self._log, p.Accounts())
        sums = a.SumCategories(self._settings.cats)
        a.DumpSums(sums, self._settings.baseline, self._settings.account_names)
        
        months, monthly_cats = a.SumMonth(self._settings.cats)
        a.DumpMonth(months, monthly_cats)

        

    def Close(self):
        """
        Close whatever is needed before leaving.
        """
        self._log.Close()

#------------------------
def main():
    r = Expenses()
    r.ParseArgs(sys.argv)
    r.Run()
    r.Close()

if __name__ == "__main__":
    main()

#------------------------
# Local Variables:
# mode: python
# tab-width: 4
# py-continuation-offset: 4
# py-indent-offset: 4
# sentence-end-double-space: nil
# fill-column: 79
# End:
